import { reactive } from "vue";
import router from "@/router/index";
import { page as allergyPage } from "@/api/allergy";
import { page as diseasePage } from "@/api/disease";
import { add, update, getById } from "@/api/recipe";
import { page as recipeTypePage } from "@/api/recipeType";
import { ElMessage } from "element-plus";

const uploadServerUrl = `${import.meta.env.VITE_API_SERVER}`;
export const $refs = reactive([]);

export const _$ = reactive({
  state: {
    previewDialogVisible: false,
    dialogImageUrl: "",
  },
  requestParam: {
    id: null,
  },
  headers: {
    Authorization: `Bearer ${localStorage.getItem("ats-user-token")}`,
  },
  images: [],
  fileList: [],
  allergies: [],
  diseases: [],
  recipeTypes: [],
  responseParam: {},
  rules: reactive({}),
});

export const $ = {
  init(refs) {
    if (refs) {
      $refs.length = 0;
      refs.forEach((ref) => {
        $refs.push(ref);
      });
    }
    allergyPage({
      pageNum: 0,
      pageSize: 100,
      condition: "",
    }).then((data) => {
      if (data) {
        _$.allergies.push(...data.records);
      }
    });
    diseasePage({
      pageNum: 0,
      pageSize: 100,
      condition: "",
    }).then((data) => {
      if (data) {
        _$.diseases.push(...data.records);
      }
    });
    recipeTypePage({
      pageNum: 0,
      pageSize: 100,
      condition: "",
    }).then((data) => {
      if (data) {
        _$.recipeTypes.push(...data.records);
      }
    });
  },

  async onSubmit(formEl) {
    if (!formEl) {
      return;
    }
    await formEl.validate((valid, fields) => {
      if (valid) {
        _$.requestParam.images = _$.images.join(",");

        const recipeAllergyList = [];
        const recipeCureAllergyList = [];
        const recipeCureDiseaseList = [];
        const recipeDiseaseList = [];

        _$.requestParam.recipeAllergyList.forEach((item) => {
          recipeAllergyList.push({
            allergyId: item,
          });
        });
        _$.requestParam.recipeCureAllergyList.forEach((item) => {
          recipeCureAllergyList.push({
            allergyId: item,
          });
        });
        _$.requestParam.recipeCureDiseaseList.forEach((item) => {
          recipeCureDiseaseList.push({
            diseaseId: item,
          });
        });
        _$.requestParam.recipeDiseaseList.forEach((item) => {
          recipeDiseaseList.push({
            diseaseId: item,
          });
        });

        _$.requestParam.recipeAllergyList = recipeAllergyList;
        _$.requestParam.recipeCureAllergyList = recipeCureAllergyList;
        _$.requestParam.recipeCureDiseaseList = recipeCureDiseaseList;
        _$.requestParam.recipeDiseaseList = recipeDiseaseList;

        if (router.currentRoute.value.query.id) {
          update(_$.requestParam)
            .then((_) => {
              ElMessage({
                message: "修改成功",
                type: "success",
              });
            })
            .then((_) => {
              router.push("/manage/recipe");
            });
        } else {
          add(_$.requestParam)
            .then((_) => {
              ElMessage({
                message: "新增成功",
                type: "success",
              });
            })
            .then((_) => {
              router.push("/manage/recipe");
            });
        }
      } else {
        console.log("校验失败！", fields);
      }
    });
  },

  onReset() {
    $.loadEdit();
  },

  loadEdit() {
    getById(router.currentRoute.value.query.id).then((data) => {
      _$.requestParam = data;
      _$.requestParam.images.split(",").forEach((item) => {
        _$.images.push(`${item}`);
        _$.fileList.push({
          url: `${uploadServerUrl}${item}?Authorization=Bearer ${localStorage.getItem(
            "ats-user-token"
          )}`,
        });
      });

      const recipeAllergyList = [];
      const recipeCureAllergyList = [];
      const recipeCureDiseaseList = [];
      const recipeDiseaseList = [];

      _$.requestParam.recipeAllergyList.forEach((item) => {
        recipeAllergyList.push(item.id);
      });
      _$.requestParam.recipeCureAllergyList.forEach((item) => {
        recipeCureAllergyList.push(item.id);
      });
      _$.requestParam.recipeCureDiseaseList.forEach((item) => {
        recipeCureDiseaseList.push(item.id);
      });
      _$.requestParam.recipeDiseaseList.forEach((item) => {
        recipeDiseaseList.push(item.id);
      });

      _$.requestParam.recipeAllergyList = recipeAllergyList;
      _$.requestParam.recipeCureAllergyList = recipeCureAllergyList;
      _$.requestParam.recipeCureDiseaseList = recipeCureDiseaseList;
      _$.requestParam.recipeDiseaseList = recipeDiseaseList;
    });
  },

  handleSizeChange(val) {
    _$.supplier.responseParam.pageSize = val;
    $.loadSuppliers();
  },

  handleCurrentChange(val) {
    _$.supplier.responseParam.pageNum = val;
    $.loadSuppliers();
  },

  handleSelectionChange(e) {
    _$.supplierSelected.length = 0;
    _$.supplierSelected.push(...e);
  },

  onPreview(uploadFile) {
    _$.state.dialogImageUrl = uploadFile.url;
    _$.state.previewDialogVisible = true;
  },

  onUploadSuccess(response) {
    if (response.code === 200) {
      _$.images.push(response.data);
    }
  },

  onRemove(uploadFile, uploadFiles) {
    _$.images.forEach((item, index) => {
      if (uploadFile.url.indexOf(item) > -1) {
        _$.images.splice(index, 1);
      }
    });
  },

  clean() {
    _$.requestParam = {};
    _$.fileList.length = 0;
    _$.images.length = 0;
    _$.allergies.length = 0;
    _$.diseases.length = 0;
    _$.recipeTypes.length = 0;
    $refs.length = 0;
  },
};

export const to = {};
